<template>
  <div
    :class="unStatus === false ? 'tzy-selected-pop' : 'tzy-selected-popTabs'"
  >
    <div class="tzy-selected-pop__left" @click="unfoldChange">
      <div class="tzy-selected-pop__left-info">
        <el-icon
          v-if="unStatus === false"
          color="#fff"
          style="margin-left: 14px"
        >
          <DArrowLeft />
        </el-icon>
        <el-icon v-else color="#fff" style="margin-left: 14px">
          <DArrowRight />
        </el-icon>
        <div class="tzy-selected-pop__text">志愿表</div>
        <div class="tzy-selected-pop__num">
          {{ volunteerInfos.length }}
        </div>
      </div>
      <div class="uzy-button save" @click.stop="onClickSaveVolunteer">保存</div>
      <div class="uzy-button save" @click.stop="onClickTop">顶部</div>
    </div>
    <div class="tzy-selected-pop__content-right">
      <el-input
        v-model="searchKey"
        style="max-width: 600px"
        placeholder=""
        class="height40"
        @keyup.enter="handleEnter"
        @input="searchInputChange"
      >
        <template #append>
          <el-button type="primary" @click="handleEnter">搜索</el-button>
        </template>
      </el-input>
      <el-scrollbar ref="listRef" class="tzy-content-list margintop">
        <VueDraggable
          ref="el"
          v-model="volunteerInfos"
          :animation="150"
          ghostClass="ghost"
          class="flex-col gap-2 p-4 w-300px h-300px m-auto bg-gray-500/5 rounded"
          @end="draggableEnd"
        >
          <div
            class="tzy-contetn-list-date"
            v-for="(data, index) in volunteerInfos"
            :key="data.collegeData.id"
          >
            <div class="between">
              <div
                class="between"
                style="width: 86%; display: flex; flex-direction: row"
              >
                <div
                  class="tzy-content-number"
                  :class="
                    data.collegeData.chance_lv == 1
                      ? 'chance1'
                      : data.collegeData.chance_lv == 2
                        ? 'chance2'
                        : 'chance3'
                  "
                >
                  {{ data.key }}
                </div>
                <div
                  class="tzy-content-name"
                  v-html="searchHandle(data.collegeData.collegeName)"
                ></div>
              </div>

              <el-icon size="16" class="curr">
                <Rank />
              </el-icon>
              <el-popconfirm
                confirm-button-text="删除"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="确认删除"
                @confirm="onClickDeleteCollege(index)"
              >
                <template #reference>
                  <el-icon class="curr" size="16">
                    <Delete />
                  </el-icon>
                </template>
              </el-popconfirm>
            </div>
            <div
              class="between margintop"
              v-for="(major, idx) in data.majorsInfo"
              :key="idx"
            >
              <div>
                <span class="sizeName">{{ idx + 1 }}</span>
                <div
                  class="tzy-contetn-name"
                  v-html="searchHandle(major.professionRealName)"
                ></div>
              </div>
              <el-icon
                size="18"
                color="#ccc"
                class="curr"
                @click="onClickDeleteMajor(index, idx)"
              >
                <Close />
              </el-icon>
            </div>
          </div>
        </VueDraggable>
      </el-scrollbar>
      <el-button
        type="primary"
        class="height40"
        style="width: 100%; background-color: #165dff"
        @click="onClickSaveVolunteer"
        >保存志愿表（{{ volunteerInfos.length }}）</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { VueDraggable } from 'vue-draggable-plus';

import { computed, ref } from 'vue';
import volunteersStore from '@/store/modules/volunteerInfos';
import { ElMessage } from 'element-plus';
import { zySave } from '/src/api/appv2/appv2.js';
import { useRouter } from 'vue-router';
import { watch } from 'vue';

const emit = defineEmits(['onClickTop']);

const router = useRouter();
const volunteerStore = volunteersStore();

const volunteerInfos = ref([]);
const storeVolunteerInfos = computed(() => volunteerStore.volunteerInfos);
const keys = ref([]);

const listRef = ref(null);
const unStatus = ref(false);
const searchKey = ref('');

const props = defineProps({
  studentData: {
    type: Object,
    default: {},
  },
  batchInfo: {
    type: Object,
    default: {},
  },
});

watch(
  storeVolunteerInfos,
  (newVal) => {
    let arr = [];
    keys.value = Object.keys(newVal);

    for (let key in newVal) {
      let info = newVal[key];
      info.key = key;
      arr.push(info);
    }

    volunteerInfos.value = arr;
  },
  { immediate: true }
);

function unfoldChange() {
  unStatus.value = !unStatus.value;
}

// 拖拽排序结束
function draggableEnd(event) {
  if (event.oldIndex != event.newIndex) {
    volunteerInfos.value.forEach((item, index) => {
      item.key = keys.value[index];
    });

    setVolunteerInfos();
  }
}

function searchInputChange() {
  currentIndex.value = 0;
  setTimeout(() => {
    handleEnter();
  }, 100);
}

let currentIndex = ref(0);
const validElements = ref([]);
// 有时候DOM会多出来一个offsetTop为0的元素  这里过滤掉这个为0的元素 否则会有问题
const handleEnter = () => {
  validElements.value = document.querySelectorAll('.spanHighlight');
  if (validElements.value.length > 0) {
    validElements.value = Array.from(validElements.value).filter(
      (element) => element.offsetTop !== 0
    );
    if (validElements.value.length > 0) {
      currentIndex.value = currentIndex.value % validElements.value.length;
      if (currentIndex.value > 0) {
        validElements.value[currentIndex.value - 1].classList.remove(
          'highlightBackGround'
        ); // 移除前一个高亮元素的背景色
      } else {
        validElements.value[validElements.value.length - 1].classList.remove(
          'highlightBackGround'
        ); // 移除最后一个高亮元素的背景色
      }
      const targetElement = validElements.value[currentIndex.value];
      targetElement.classList.add('highlightBackGround'); // 添加背景颜色

      listRef.value.scrollTo({
        top: targetElement.offsetTop,
        behavior: 'smooth',
      });

      currentIndex.value++; // 更新索引，准备下次跳转
    }
  }
};

// 搜索关键字修改颜色
function searchHandle(val) {
  let text = val; // 初始状态下设为普通文本

  if (searchKey.value) {
    var reg = new RegExp('(' + searchKey.value + ')', 'g');
    text = val.replace(reg, (match) => {
      return `<span ref="spanRef"  id="spanHighlight" class="spanHighlight" style='color:#165dff ;font-weight:bolder'>${match}</span>`;
    });
  }
  return text;
}

// 点击删除填报的院校
function onClickDeleteCollege(index) {
  // delete volunteerInfos.value[key];
  const keys = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];

  let allKey = volunteerInfos.value.map((item) => item.key);

  volunteerInfos.value.splice(index, 1);

  const volunteerKey = volunteerInfos.value[index].key;

  keys.forEach((key) => {
    if (volunteerKey.includes(key)) {
      const keyArr = allKey.filter((item) => item.includes(key));
      const i = keyArr[keyArr.length - 1];

      allKey = allKey.filter((item) => item != i);
    }
  });

  volunteerInfos.value.forEach((item, index) => {
    item.key = allKey[index];
  });

  setVolunteerInfos();
}

// 点击删除填报的院校专业
function onClickDeleteMajor(index, idx) {
  volunteerInfos.value[index].majorsInfo.splice(idx, 1);
  setVolunteerInfos();
}

function setVolunteerInfos() {
  let infos = {};
  volunteerInfos.value.forEach((item) => {
    infos[item.key] = item;
    delete infos[item.key]['key'];
  });
  volunteerStore.setVolunteerInfos(infos);
}

// 点击保存志愿表
function onClickSaveVolunteer() {
  setVolunteerInfos();
  let volunteerInfo = volunteerStore.volunteerInfos;
  let keys = []; //Object.keys(volunteerInfo);
  let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];

  let rate = 0;
  let isHaveMajor = true;
  Object.keys(volunteerInfo).forEach((key) => {
    const college = volunteerInfo[key].collegeData;
    const majorsInfo = volunteerInfo[key].majorsInfo || [];
    rate = rate + Number(college.chance);

    if (majorsInfo.length == 0) {
      isHaveMajor = false;
    }

    arr.forEach((item) => {
      if (key == item) {
        keys.push(key);
      }
    });
  });

  if (keys.length < 3) {
    ElMessage({
      message: '至少填报三个院校',
      type: 'warning',
    });
    return;
  }

  let continuityKeys = keys.join('');

  let isContinuous = true;
  continuityKeys = continuityKeys.toLowerCase(); // 将字符串转换为小写字母

  for (let i = 0; i < continuityKeys.length - 1; i++) {
    let currentCharCode = continuityKeys.charCodeAt(i);
    let nextCharCode = continuityKeys.charCodeAt(i + 1);
    if (nextCharCode - currentCharCode !== 1) {
      isContinuous = false; // 不是连续字母
    }
  }

  if (isContinuous == false) {
    ElMessage({
      message: '填报的志愿需要依次选择并且是连续的',
      type: 'warning',
    });
    return;
  }

  if (isHaveMajor == false) {
    ElMessage({
      message: '请至少填报一个专业',
      type: 'warning',
    });
    return;
  }

  rate = (rate / keys.length).toFixed(0);
  rate = rate + '%';

  let studentInfo = props.studentData.student;
  let data = {
    createFrom: 1, // 老师填写
  };
  data['studentId'] = props.studentData.studentId;

  if (studentInfo.section.length > 0) {
    data['family'] =
      studentInfo.score +
      '分 ' +
      studentInfo.section +
      '位 ' +
      studentInfo.sgname +
      ' ' +
      props.batchInfo.batch;
  } else {
    data['family'] =
      studentInfo.score +
      '分 ' +
      studentInfo.sgname +
      ' ' +
      props.batchInfo.batch;
  }
  data['score'] = studentInfo.score;
  data['sgname'] = studentInfo.sgname;
  data['section'] = studentInfo.section;
  data['batch'] = props.batchInfo.batch;
  data['createFrom'] = 1;

  data['zy_type'] = 3;
  data['isTeacherSee'] = 1;
  data['isStudentSee'] = 0;
  data['volunteerInfos'] = JSON.stringify(volunteerInfo);
  data['rate'] = rate;
  zySave(data).then((ref) => {
    let body = JSON.stringify({
      index: ref.data.index,
      zy_type: 3,
      studentData: props.studentData,
    });
    router.push({
      path: '/leader/savevolunteer',
      query: {
        data: body,
      },
    });
  });
}

// 点击回到顶部
function onClickTop() {
  emit('onClickTop');
}

defineExpose({
  unfoldChange,
});
</script>
<style lang="scss" scoped>
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.tzy-selected-popTabs {
  right: 10px;
  position: fixed;
  top: 64px;
  width: 400px;
  height: 200px;
  z-index: 2000;
  transform: translateX(0px);
  transition: transform 0.6s;
  display: flex;

  .tzy-selected-pop__content-right {
    flex: 1;
    background: #fff;
    border-radius: 0 0 0 4px;
    padding: 20px;
    overflow: hidden;
    box-shadow: -10px 0 10px 0 rgba(0, 0, 0, 0.05);
    height: calc(100vh - 100px);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;

    .tzy-content-list {
      flex: 1;
      width: 100%;
      overflow-x: hidden;
      overflow-y: auto;

      .tzy-contetn-list-date {
        background: #f7f8fa;
        border-radius: 4px 4px 4px 4px;
        padding: 12px;
        margin-bottom: 10px;

        .tzy-contetn-name {
          display: inline-block;
          padding-right: 10px;
          font-size: 14px;
          font-weight: 400;
          color: #4e5969;
          line-height: 20px;
        }

        .sizeName {
          font-size: 14px;
          font-weight: 400;
          padding-right: 10px;
          color: #212121;
        }

        .tzy-content-number {
          text-align: center;
          // background-color: #F53F3F;
          color: #ffffff;
          min-width: 23px;
          height: 22px;
          line-height: 22px;
          border-radius: 4px;
        }

        .tzy-content-name {
          margin-left: 12px;
        }
      }
    }
  }

  .tzy-selected-pop__left {
    width: 48px;
    height: 246px;
    cursor: pointer;
    position: absolute;
    left: -48px;
    top: 106px;

    .uzy-button {
      width: 48px;
      height: 42px;
      font-size: 16px;
      font-weight: 400;
      line-height: 42px;
      background-color: #ffffff;
      text-align: center;
      color: #165dff;
      border: 1px solid #165dff;
    }

    .tzy-selected-pop__left-info {
      padding-top: 16px;
      border: 1px solid transparent;
      border-right: none;
      border-top-left-radius: 4px;
      background: #165dff;

      .tzy-selected-pop__text {
        width: 16px;
        height: 66px;
        font-size: 16px;
        font-weight: 400;
        color: #fff;
        margin: 0 auto;
        line-height: 22px;
        margin-bottom: 8px;
      }

      .tzy-selected-pop__num {
        text-align: center;
        font-size: 24px;
        font-family:
          PingFang SC-Semibold,
          PingFang SC;
        font-weight: 600;
        color: #fff;
        line-height: 24px;
        margin-bottom: 16px;
      }
    }
  }
}

.tzy-selected-pop {
  right: 10px;
  position: fixed;
  top: 64px;
  width: 400px;
  height: 200px;
  z-index: 2000;
  transform: translateX(400px);
  transition: transform 0.6s;
  display: flex;

  .tzy-selected-pop__content-right {
    flex: 1;
    background: #fff;
    border-radius: 0 0 0 4px;
    padding: 20px;
    overflow: hidden;
  }

  .tzy-selected-pop__left {
    width: 48px;
    height: 246px;
    cursor: pointer;
    position: absolute;
    left: -48px;
    top: 106px;

    .uzy-button {
      width: 48px;
      height: 42px;
      font-size: 16px;
      font-weight: 400;
      line-height: 42px;
      background-color: #ffffff;
      text-align: center;
      color: #165dff;
      border: 1px solid #165dff;
    }

    .tzy-selected-pop__left-info {
      padding-top: 16px;
      border: 1px solid transparent;
      border-right: none;
      border-top-left-radius: 4px;
      background: #165dff;

      .tzy-selected-pop__text {
        width: 16px;
        height: 66px;
        font-size: 16px;
        font-weight: 400;
        color: #fff;
        margin: 0 auto;
        line-height: 22px;
        margin-bottom: 8px;
      }

      .tzy-selected-pop__num {
        text-align: center;
        font-size: 24px;
        font-family:
          PingFang SC-Semibold,
          PingFang SC;
        font-weight: 600;
        color: #fff;
        line-height: 24px;
        margin-bottom: 16px;
      }
    }
  }
}

.chance1 {
  background-color: #f53f3f;
}

.chance2 {
  background-color: #ff8c33;
}

.chance3 {
  background-color: #00bf10;
}
</style>

<style>
.highlightBackGround {
  background: #165dff;
  color: #fff !important;
}
</style>
